
from matplotlib.figure import Figure 
from matplotlib import cm
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

import numpy as np
import pandas as pd
from scipy.stats import pearsonr

def box(data, title=None, size=(30, 10), saveas='out.pdf'):

	fig=Figure(figsize=[10,10], facecolor='w')
	canvas = FigureCanvas(fig)
	ax=fig.add_axes([.1,.1,.8,.8]) 
	
	ax.set_title(title)

	a,b=size

	# TODO: make fig size suitable for different plots
	fig.set_size_inches(a, b)
	df=data
	d=[]
	xticks=df.columns
	#color=[]
	## TODO: use getCtrlcolor instead
	#if ctrl is not None:
	#        for label in df.index:
	#                if label in ctrl:
	#                        color.append('r')
	#                else:
	#                        color.append('w')

	for icol in range(len(df.columns)):
		d.append(df.iloc[:, icol].values.ravel())
	ax.boxplot(d, sym='')
	#df.boxplot(ax=ax, sym='')
	for i in range(len(d)):
		x=[i+1 for j in range(len(d[0]))]
		jitter=np.random.normal(x, 0.1)
		ax.scatter(jitter,d[i], alpha=0.2)
	ax.set_xticklabels(tuple(xticks), rotation='vertical')
	
	fig.savefig(saveas, bbox_inches='tight')


def scatter(x, y, c='w', title=None, xlabel='', ylabel='', saveas='out.pdf'):
	fig=Figure(figsize=[10,10], facecolor='w')
	canvas = FigureCanvas(fig)
	ax=fig.add_axes([.1,.1,.8,.8]) 
	ax.set_title(title)
	ax.set_xlabel(xlabel)
	ax.set_ylabel(ylabel)  
	ax.scatter(x, y, c=c)

	x_vals=x.values.ravel()
	y_vals=y.values.ravel()
	
	df=pd.DataFrame({'x':x_vals, 'y':y_vals})
	df=df.dropna()


	corr, p = pearsonr(df['x'].values, df['y'].values)

	ax.annotate('corr:'+str(round(corr, 5)), xy=(0.05, 0.60), xycoords='axes fraction')
	ax.annotate('pval:'+str(p) , xy=(0.05, 0.65), xycoords='axes fraction')
	
	fig.savefig(saveas, bbox_inches='tight')
